﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Pivot;

namespace PivotPhysics_Viewer
{
    public partial class MainPage : UserControl
    {
        /// <summary>
        /// Keeps track of all the known collections
        /// </summary>
        /// 
        public ObservableCollection<PlotCollectinInfo> KnownPlotCollections { get; set; }

        private PivotNavagationTracker _navTracker;

        public MainPage()
        {
            InitQuickData();
            InitializeComponent();
            DataContext = this;

            ///
            /// Now, get the pivot viewer navagation monitor hooked up.
            /// 

            _navTracker = new PivotNavagationTracker(MainViewer);
            MoveBackButton.Command = _navTracker.MoveBackCommand;
            MoveForwardButton.Command = _navTracker.MoveForwardCommand;
        }

        /// <summary>
        /// Called on the UI thread to get the collection selected and the PV showing the same thing.
        /// </summary>
        private void SyncUpViewerCollection()
        {
            ///
            /// Get out the collection that is currently selected
            /// 

            var pCollection = CollectionChooser.SelectedItem as PlotCollectinInfo;
            if (pCollection == null)
            {
                return;
            }

            var uri = pCollection.uri;

            ///
            /// Ok - start off the loading...
            /// 

            MainViewer.LoadCollection(uri, "");
        }

        /// <summary>
        /// We are called very early in the ctor process. We should not be doing any network or similar
        /// types of transactions. We should be VERY fast.
        /// </summary>
        private void InitQuickData()
        {
            ///
            /// Get the list of collections that we already know about (isolated storage, for example)
            /// 

            KnownPlotCollections = new ObservableCollection<PlotCollectinInfo>(KnownCollections.LoadCollectionList());

            ///
            /// Go out on the net and load up the latest rendered set.
            /// 

            var wc = new WebClient();
            wc.DownloadStringCompleted += (s, o) =>
            {
                if (o.Error != null)
                {
                    return;
                }
                var lst = from cNameFull in o.Result.Split(new char[] { ' ', '\r', '\n' })
                          let cName = cNameFull.Trim()
                          where cName.Length > 0
                          select cName;

                var collection = KnownCollections.CreateListFromStrings(lst.ToArray());
                var selectedObj = (CollectionChooser.SelectedValue as PlotCollectinInfo);
                string currentlySelectedName = selectedObj == null ? "" : selectedObj.Name;
                KnownPlotCollections.Clear();
                int index = 0;
                int foundIndex = 0;
                foreach (var item in collection)
                {
                    KnownPlotCollections.Add(item);
                    if (item.Name == currentlySelectedName)
                    {
                        foundIndex = index;
                    }
                    index++;
                }

                if (foundIndex == 0)
                    foundIndex = 1;

                if (foundIndex <= KnownPlotCollections.Count)
                    CollectionChooser.SelectedIndex = foundIndex;

                KnownCollections.SaveCollectionList(collection);
            };
            wc.DownloadStringAsync(new Uri(new Uri(KnownPlotCollections[0].uri), "classes.txt"));
        }

        /// <summary>
        /// Called when the selection changes in the list that contols what data we are looking at.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CollectionChooser_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SyncUpViewerCollection();
        }

        /// <summary>
        /// Called when this main control is loaded. That is out queue to make sure to select
        /// something to be looking at.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            ///
            /// Select the most recent year (or recent), which should be the second thing on the list
            /// 

            CollectionChooser.SelectedIndex = 1;

            ///
            /// Start up the SL update experience
            /// 

            Application.Current.CheckAndDownloadUpdateCompleted += (s, evtarg) => UpdateCheck(evtarg);
            Application.Current.CheckAndDownloadUpdateAsync();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        private void UpdateCheck(CheckAndDownloadUpdateCompletedEventArgs e)
        {
            if (e.UpdateAvailable)
            {
                MessageBox.Show("An update to the 'Collider Plot Explorer' has been downloaded and will run nextime you restart this app!");
            }
        }

        /// <summary>
        /// A link was clicked - and it ins't in this collection we are currently looking at. So now we'll have to ask the
        /// user about it to open it (depending if we are OOB or not).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainViewer_LinkClicked(object sender, LinkEventArgs e)
        {
            if (Application.Current.InstallState == InstallState.Installed)
            {
                OpenURL.OpenBrowserWithURL(e.Link);
            }
            else
            {
                MessageBox.Show("To open this web page in your default browser you have to install this application on your machine. To do this, click 'OK' and then right click anywhere in the plot browser and select the 'Install' option.");
            }
        }
    }
}
